package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import util.ImageUtil;
import util.JsonWrapper;
import util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * @author fzh
 * @since 2017/11/2
 */
@WebServlet(name = "ImageServlet", urlPatterns = {"/admin/image", "/user/image"})
public class ImageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (items != null) {
            // check items
            Iterator itr = items.iterator();
            String imageName;
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (!item.isFormField() && !"".equals(item.getName())) {
//		是文件，且文件名不空，即用户选择了文件
                    try {
                        imageName = ImageUtil.getImageName(item.getName().split("\\.")[1]);  //自行车图片名
                        String filePath = ImageUtil.INSTANCE.getImagePath() + imageName;  //自行车图片存储
//		上传文件
                        item.write(new File(this.getServletContext().getRealPath("/") + filePath));
                        ResponseUtil.write(response, JsonWrapper.builder().setStatus(200).setMsg("success").setDataEntry("url", filePath).build());
                    } catch (Exception e) {
                        ResponseUtil.write(response, JsonWrapper.builder().setStatus(301).setMsg("failed").build());
                    }
                }
            }
        } else {
            ResponseUtil.writeBadRequest(response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ResponseUtil.writeBadRequest(response);
    }
}
